/*
 * 
 */
package co.edu.udistrital.erpgrid.utilidades.consola;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import expectj.ExpectJ;
import expectj.ExpectJException;
import expectj.Spawn;
import expectj.TimeoutException;

/**
 * La Clase Consola para la ejecucion de comandos.
 */
public class Consola {

	 /** El RS. */
 	private static transient ResourceBundle RS = ResourceBundle
	 .getBundle("utilidadesConf");

	/** La Constante LOG. */
	private static final Logger LOG = LoggerFactory.getLogger(Consola.class);

	/**
	 * Ejecutar comando de globus especificado en la consola con la ip especificada
	 *
	 * @param comando el comando a ejecutar
	 * @param ip la ip del nodo de globus
	 * @return el string con el resultado de la ejecución
	 * @throws Exception 
	 */
	public static String ejecutarComando(String comando, String ip) throws Exception {
		String s;
		StringBuilder resultado = new StringBuilder();
		// Determinar en qué SO estamos
		String so = System.getProperty("os.name");
		// Comando para Linux
		if (!so.equals("Linux"))
			throw new Exception("No soportado");

		try {

			boolean okProxy = verificarProxy();
//			boolean okProxy = false;

			// Talk to it
			if (!okProxy){
				
				// Create a new ExpectJ object with a timeout of 5s
				ExpectJ expectinator = new ExpectJ();

				// Fork the process
				Spawn shell = expectinator.spawn("/bin/sh");
				
				shell.send("LD_LIBRARY_PATH=/opt/gt4/lib grid-proxy-init\n");
				shell.expect("Enter GRID pass phrase for this identity:");
				shell.send("globus\n");
				shell.expectErr("Done");
				shell.send("exit\n");
				shell.expectClose();
				
			}
			
			String globus_hostname = "";
				globus_hostname = "GLOBUS_HOSTNAME="+RS.getString("principal.hostname")+" ";
			
			String send = globus_hostname +"LD_LIBRARY_PATH=/opt/gt4/lib globusrun-ws -s -submit " +
			"-F https://"+ip.trim()+"/wsrf/services/ManagedJobFactoryService "
			+"-c "+ comando + "";
			
			LOG.info("***************************************COMANDO***************************************");
			LOG.info(send);
			LOG.info("***************************************COMANDO***************************************");
			
			File archivoComando = File.createTempFile("globus", ".job");
			archivoComando.setExecutable(true);
			
			OutputStream os = new FileOutputStream(archivoComando);
			os.write(send.getBytes());
			os.close();
			
			 // // Ejcutamos el comando
			  Process p = Runtime.getRuntime().exec(archivoComando.getPath());

			 BufferedReader stdInput = new BufferedReader(new
			 InputStreamReader(p.getInputStream()));
			 //
			  BufferedReader stdError = new BufferedReader(new
			 InputStreamReader(p.getErrorStream()));
			 
			  //las salidas de globus se visualizan en el log de error.
			  while ((s = stdInput.readLine()) != null) {
				  resultado.append(s);
				  LOG.info(s);
			  }
			  while ((s = stdError.readLine()) != null) {
				  if(s.equals("Delegating user credentials...Failed.")){
					  resultado = new StringBuilder();
					  break;
				  }
				  resultado.append(s);
				  LOG.info(s);
			  }
		} catch (Exception e) {
			 resultado = new StringBuilder();
			LOG.error(e.getMessage(), e);
		}
		return resultado.toString();
	}

	/**
	 * Verificar proxy de globus.
	 *
	 * @return verdadero, si es satisfactorio
	 */
	private static boolean verificarProxy(){
		
		boolean ok = false;
		// file.proxy /tmp/x509up_u1001
		//buscar archivo de proxy
		File file = new File(RS.getString("file.proxy"));
		if(file.exists()){
			ok = true;
		}
		return ok;
		
	}

}
